// src/components/Header/index.js

import React, { useEffect } from "react";
import { Layout, Button, Dropdown, Menu, Avatar, message, Badge } from "antd";
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
  DownOutlined,
  LogoutOutlined,
  LockOutlined,
  MessageOutlined,
} from "@ant-design/icons";
import { useSelector, useDispatch } from "react-redux";
import { toggleCollapsed, toggleTheme } from "../../store/layoutSlice";
import { logout } from "../../store/userSlice";
import { fetchUnreadMessageCount } from "../../store/customerServiceSlice";
import { useHistory } from "react-router-dom";
import styled from "styled-components";

const { Header } = Layout;

// 样式化的Header组件
const StyledHeader = styled(Header)`
  padding: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: ${(props) => props.theme.headerBgColor};
  color: ${(props) => props.theme.textColor};
`;

// 样式化的用户信息区域
const UserInfo = styled.div`
  margin-right: 20px;
  cursor: pointer;
  color: ${(props) => props.theme.textColor};
`;

const AppHeader = () => {
  const dispatch = useDispatch();
  const history = useHistory();

  // 从Redux store中获取状态
  const { collapsed, currentTheme } = useSelector((state) => state.layout);
  const { userName } = useSelector((state) => {
    return state.user
  });

  const { unreadMessageCount = 0 } = useSelector((state) => state.customerService);

  // 定期获取未读消息数
  useEffect(() => {
    const interval = setInterval(() => {
      dispatch(fetchUnreadMessageCount());
    }, 30000); // 每30秒更新一次

    return () => clearInterval(interval);
  }, [dispatch]);

  // 处理退出登录
  const handleLogout = async () => {
    try {
      await dispatch(logout()).unwrap();
      message.success("退出登录成功");
      history.push("/login");
    } catch (error) {
      message.error("退出登录失败: " + (error.message || "未知错误"));
    }
  };

  // 处理修改密码
  const handleChangePassword = () => {
    history.push("/change-password");
  };

  // 处理客服消息
  const handleCustomerService = () => {
    history.push("/customerService/messages");
  };
  // 操作栏样式
  const optionStyle = {display:'flex',alignItems:'center'}
  // 用户下拉菜单
  const menu = (
    <Menu theme={currentTheme.type}>
      <Menu.Item key="1" onClick={handleChangePassword} icon={<LockOutlined />}>
        修改密码
      </Menu.Item>
      <Menu.Item key="2" onClick={handleLogout} icon={<LogoutOutlined />}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <StyledHeader theme={currentTheme}>
      <div>
        {/* 折叠/展开侧边栏按钮 */}
        {React.createElement(
          collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
          {
            className: "trigger",
            onClick: () => dispatch(toggleCollapsed()),
            style: { color: currentTheme.textColor },
          }
        )}
        {/* 切换主题按钮 */}
        <Button
          onClick={() => dispatch(toggleTheme())}
          style={{ marginLeft: 16 }}
        >
          切换主题
        </Button>
      </div>
      <div style={optionStyle}>
        {/* 客服消息按钮 */}
        <Badge count={unreadMessageCount || 0} style={{ marginRight: 24 }}>
          <Button
            icon={<MessageOutlined />}
            onClick={handleCustomerService}
            style={{ color: currentTheme.textColor }}
          >
            客服消息
          </Button>
        </Badge>
        {/* 用户信息下拉菜单 */}
        <UserInfo theme={currentTheme}>
          <Dropdown overlay={menu} trigger={["click"]}>
            <span>
              <Avatar
                icon={<UserOutlined />}
                style={{
                  marginRight: 8,
                  backgroundColor: currentTheme.primaryColor,
                }}
              />
              {userName} <DownOutlined />
            </span>
          </Dropdown>
        </UserInfo>
      </div>
    </StyledHeader>
  );
};

export default AppHeader;